package com.jiusit.golf.api;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.webbuilder.tool.Encrypter;

/**
 * 客户端请求工具类
 * @author chenpy
 *
 */

public class HttpClientUtil {

	private static int ConnectionTimeout=30000; 
	private static int SoTimeout=30000;
	
	private static HttpClientUtil m_instance = new HttpClientUtil();
	
	private HttpClientUtil() {
		
	}
	
	public synchronized static HttpClientUtil getInstance() {
		return m_instance;
	}
	public static String getSign(String url,String data,String appmarst){
		try {
			System.out.println(data);
			@SuppressWarnings({ "deprecation", "resource" })
			HttpClient client = new DefaultHttpClient();
			String sign=org.apache.commons.codec.digest.DigestUtils.md5Hex(("POST"+"http://msg.umeng.com/api/send"+data+appmarst).getBytes("utf8"));
			//String sign=Encrypter.getMD5();
			sign=sign.toLowerCase();
			url =url+"?sign="+sign;
			 HttpPost post = new HttpPost(url);
			 post.setHeader("User-Agent",  "Mozilla/5.0");
			 StringEntity se = new StringEntity(data, "UTF-8");
			 post.setEntity(se);
			 HttpResponse response = client.execute(post);
			  int status = response.getStatusLine().getStatusCode();
		        System.out.println("Response Code : " + status);
		        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		        StringBuffer result = new StringBuffer();
		        String line = "";
		        while ((line = rd.readLine()) != null) {
		            result.append(line);
		        }
		        System.out.println(result.toString());
		        if (status == 200) {
		            System.out.println("发送成功");
		        }else {
		            System.out.println("发送失败");
		        }
			return result.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "";
	}
	
	
	public static String PostExecute(String url,List<NameValuePair> nvpPar){
		CloseableHttpClient client=HttpClients.createDefault();
		CloseableHttpResponse closeableHttpResponse=null;
		HttpPost httpPost = new HttpPost(url);
		try {
			httpPost.setConfig(RequestConfig.custom().setConnectTimeout(ConnectionTimeout).setSocketTimeout(SoTimeout).build());
			httpPost.setEntity(new UrlEncodedFormEntity(nvpPar, HTTP.UTF_8));
			closeableHttpResponse = client.execute(httpPost);
			HttpEntity entity = closeableHttpResponse.getEntity();// 获取响应实体
			String rsacontent = EntityUtils.toString(entity);// 响应内容
			return rsacontent;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			close(client,closeableHttpResponse);
		}
		return "";
	}
	
	public String GetExecute(){
		return "";
	}
	
	
	public String MultipartExecute(){
		return "";
	}
	/**
     * 以Get方法访问
     * @param url 请求地址
     * @param argsMap 请求携带参数
     * @return String
     * @throws Exception
     */
    public static String GETMethod(String url,Map<String, Object> argsMap) throws Exception{
        byte[] dataByte = null;
        HttpClient httpClient = new DefaultHttpClient();
        //为GET请求链接构造参数
        url = formatGetParameter(url,argsMap);
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            byte[] responseBytes = getData(httpEntity);
            dataByte = responseBytes;
            httpGet.abort();
        }
        //将字节数组转换成为字符串
        String result = bytesToString(dataByte);
        return result;
    }
    /**
     * 构造GET请求地址的参数拼接
     * @param url 地址
     * @param argsMap 参数
     * @return String
     */
    public static String formatGetParameter(String url,Map<String, Object> argsMap)throws Exception{
        if (url!=null && url.length()>0 && MapUtils.isNotEmpty(argsMap)) {
            if (!url.endsWith("?")) {
                url = url +"?";
            }
            if (argsMap!=null && !argsMap.isEmpty()) {
                Set<Entry<String, Object>> entrySet = argsMap.entrySet();
                Iterator<Entry<String, Object>> iterator = entrySet.iterator();
                while(iterator.hasNext()){
                    Entry<String, Object> entry = iterator.next();
                    if (entry!=null) {
                        String key = entry.getKey();
                        Object value = entry.getValue();
//                      Object value = URLEncoder.encode(entry.getValue().toString(), "UTF-8");
                        url = url + key + "=" + value;
                        if (iterator.hasNext()) {
                            url = url +"&";
                        }
                    }
                }
            }
        }
        return url;
    }
    
    /**
     * 获取Entity中数据
     * @param httpEntity
     * @return
     * @throws Exception
     */
    public static byte[] getData(HttpEntity httpEntity) throws Exception{
        BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bufferedHttpEntity.writeTo(byteArrayOutputStream);
        byte[] responseBytes = byteArrayOutputStream.toByteArray();
        return responseBytes;
    }
    
    /**
     * 将字节数组转换成字符串
     * @param bytes
     * @return
     * @throws Exception 
     */
    public static String bytesToString(byte[] bytes) throws Exception{
        if (bytes!=null) {
            String returnStr = new String(bytes,"UTF-8");
            returnStr = StringUtils.trim(returnStr);
            return returnStr;
        }
        return null;
    }
    
	private static void close(CloseableHttpClient client,CloseableHttpResponse closeableHttpResponse){
		try {
			if(closeableHttpResponse!=null){
				closeableHttpResponse.close();
			}
			if(client!=null){
				client.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
